/**
 * @author https://vue-admin-beautiful.com （不想保留author可删除）
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import router from '@/router'
import store from '@/store'
import VabProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router'
import getPageTitle from '@/utils/pageTitle'
import Vue from 'vue'
import {
  authentication,
  loginInterception,
  progressBar,
  recordRoute,
  routesWhiteList,
} from '@/config'

VabProgress.configure({
  easing: 'ease',
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
})
router.beforeEach(async (to, from, next) => {
  if (progressBar) VabProgress.start()
  let hasToken = store.getters['user/accessToken']
  let expiresTime = localStorage.getItem('expiresTime') || 0
  if (!loginInterception) hasToken = true
  // 并且token没有过期
  if (hasToken && Date.now() < expiresTime) {
    if (to.path === '/login') {
      next({ path: '/' })
      if (progressBar) VabProgress.done()
    } else {
      const hasPermissions =
        store.getters['user/permissions'] &&
        store.getters['user/permissions'].length > 0
      if (hasPermissions) {
        // intelligence 不获取权限
        if (loginInterception && authentication === 'all') {
        } else {
          Vue.prototype.$GLOBAL = []
        }
        next()
      } else {
        try {
          let permissions
          if (!loginInterception) {
            //settings.js loginInterception为false时，创建虚拟权限
            await store.dispatch('user/setPermissions', ['dram'])
            permissions = ['dram']
          } else {
            permissions = await store.dispatch('user/getUserInfo')
          }
          let accessRoutes = []

          console.log('authentication', authentication)
          if (authentication === 'intelligence') {
            // 本地的菜单
            accessRoutes = await store.dispatch('routes/setRoutes', permissions)
          } else if (authentication === 'all') {
            // 后端获取到的菜单
            accessRoutes = await store.dispatch('routes/setAllRoutes')
          }
          // console.log('accessRoutes', accessRoutes)
          // 找到的本地菜单
          let findItem = (accessItem) => {
            let arr = asyncRoutes
            let obj = arr.find(
              (itemdd) =>
                itemdd.redirect == accessItem.path ||
                itemdd.redirect == `/${accessItem.path}` ||
                itemdd.path == accessItem.path ||
                itemdd.path == `/${accessItem.path}`
            )
            // console.log('obj888', obj, accessItem)
            if (!obj) {
              return ''
            }
            let arrchildren = obj.children
            let accessChildrens = accessItem.children
            if (
              arrchildren &&
              arrchildren.length &&
              accessChildrens &&
              accessChildrens.length
            ) {
              let drr = arrchildren.filter((itemd) => {
                return accessChildrens.some((items) => {
                  return (
                    items.path == itemd.path || `/${items.path}` == itemd.path
                  )
                })
              })
              // console.log('drr', drr, obj)
              if (drr.length) {
                obj.children = drr
              }
            }
            return obj
          }
          accessRoutes.forEach((accessItem) => {
            if (authentication === 'all') {
              let obj = findItem(accessItem)
              // console.log('obj', obj)
              if (obj) {
                router.addRoute(obj)
              }
            } else {
              router.addRoute(accessItem)
            }
          })
          next({ ...to, replace: true })
        } catch {
          await store.dispatch('user/resetAccessToken')
          if (progressBar) VabProgress.done()
        }
      }
    }
  } else {
    if (hasToken) {
      Vue.prototype.$baseMessage(`登录已过期，请重新登录`, 'error');
      localStorage.clear()
    }
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (recordRoute) {
        next(`/login?redirect=${to.path}`)
      } else {
        next('/login')
      }
      if (progressBar) VabProgress.done()
    }
  }
  document.title = getPageTitle(to.meta.title)
})
router.afterEach(() => {
  if (progressBar) VabProgress.done()
})
